package com.example.noteback.studentword.controller;

import com.example.noteback.studentword.domain.Score;
import com.example.noteback.studentword.domain.Student;
import com.example.noteback.studentword.service.impl.StudentWordServiceImpl;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("studentWord")
public class StudentWordController {
    @Autowired
    private StudentWordServiceImpl studentWordService;

    @GetMapping("word")
    public HttpServletResponse word(@RequestParam("studentId") Long id,HttpServletResponse response) throws Exception {
        /** 初始化配置文件 **/
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        /** 设置编码 **/
        configuration.setDefaultEncoding("utf-8");
        /** 我的ftl文件是放在D盘的**/
        String fileDirectory = "E:\\DATA\\IDEA-2022\\note\\note-back\\src\\main\\resources\\word\\";
        /** 加载文件 **/
        configuration.setDirectoryForTemplateLoading(new File(fileDirectory));
        /** 加载模板 **/
        Template template = configuration.getTemplate("student.ftl");
        /** 准备数据 **/
        Map<String, Object> dataMap = new HashMap<>();
        //学生信息
        Student student = this.studentWordService.getStudentById(id);
        dataMap.put("number", student.getNumber());
        dataMap.put("name", student.getName());
        dataMap.put("img", getImageStr(student.getImgUrl()));

        //得分
        List<Score> scoreList = this.studentWordService.getStudentsScoreListByStudentId(id);
        //非总分
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Score score : scoreList) {
            Map<String, Object> map = new HashMap<>();
            if (score.getLocation() == 1) {
                map.put("name", score.getName());
                map.put("value", score.getValue());

                mapList.add(map);
            } else if (score.getLocation() == 2) {
                //总分
                dataMap.put("total", score.getValue());
            }
        }
        dataMap.put("score", mapList);

        //* 指定输出word文件的路径 *
        String outFilePath = "E:\\DATA\\IDEA-2022\\export\\myFreeMarker" + (System.currentTimeMillis()) + ".doc";
        //创建 myFreeMarker"+(System.currentTimeMillis())+".doc 的映射对象
        File docFile = new File(outFilePath);
        //创建输出流
        FileOutputStream fos = new FileOutputStream(docFile);
        //创建缓冲器
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        //导出word
        template.process(dataMap, out);


        /*文件下载*/
        File file = new File(outFilePath);
        // 取得文件名。
        String filename = file.getName();
        //下载
        InputStream fis = new BufferedInputStream(new FileInputStream(outFilePath));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();

        //关闭缓冲器
        if (out != null) {
            out.close();
        }
        return response;
    }

    //图片转BASE64Encoder
    public static String getImageStr(String imgFile) {
        InputStream in = null;
        byte[] data = null;
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }
}
